package com.wechat.thread;

import java.util.Iterator;
import java.util.Set;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.wechat.Exception.CustomExceptionResolver;
import com.wechat.model.Address;
import com.wechat.model.UserMessage;
import com.wechat.service.AddressService;
import com.wechat.service.UserMessageService;
public class SaveData implements Runnable{
	private UserMessageService userMessageService;
	private AddressService addressService;
	public  SaveData(UserMessageService userMessageService,AddressService addressService) {
		this.userMessageService=userMessageService;
		this.addressService=addressService;
	}
	/**
	 * 保存数据线程
	 *@dagewang 
	 *2017年11月23日
	 */
	@Override
	public void run() {
		while (true) {
			Set<Address> address = MyThread.address;
			Set<UserMessage> userMessage = MyThread.userMessage;
			if(address.size()!=0){
				Iterator<Address> iterator = address.iterator();
				while(iterator.hasNext()){
					Address next = iterator.next();
					try {
						addressService.save(next);
					} catch (Exception e) {
						Logger log=LogManager.getLogger("wechat");
						log.error(CustomExceptionResolver.getStackTrace(e));
					}
					 iterator.remove();
				}
			}
			if(userMessage.size()!=0){
				Iterator<UserMessage> iterator = userMessage.iterator();
				while(iterator.hasNext()){
					UserMessage next = iterator.next();
					try {
						userMessageService.save(next);
					} catch (Exception e) {
						Logger log=LogManager.getLogger("wechat");
						e.printStackTrace();
						log.error(CustomExceptionResolver.getStackTrace(e));
					}
					 iterator.remove();
				}
			}
			try {
				Thread.sleep(5000l);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
	}
		
}
